package com.freework.sys.dic.control;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.freework.sys.dic.service.DicServiceI;
import com.freework.sys.dic.vo.DicVO;
import com.freework.sys.table.service.TableServiceI;
import com.freework.sys.table.vo.SysDictableVO;
import com.freework.util.unmodifiableMap.KeysIndex;
import com.freework.util.unmodifiableMap.UnmodifiableKeyMap;
@Controller()
public class DicCommonContorller {
	@Resource(name="dic.table.service.TableService")
	private TableServiceI tableService=null;
	@Resource(name = "dic.service.DicService")
	private DicServiceI service = null;
	
	
	
	
	public void setTableService(TableServiceI tableService) {
		this.tableService = tableService;
	}




	public void setService(DicServiceI service) {
		this.service = service;
	}



	@ResponseBody()
	@RequestMapping("dic/DicCommonContorller/getComboData.do")
	List getComboData(String sourcetable,String sourcecolumn,String sourcedisplay,String displayField){
		try {
			if(sourcetable!=null){
			SysDictableVO table=tableService.findTableByName(sourcetable.toLowerCase());
			if(table!=null){
				
			boolean isKeycolumn=true;
			boolean isCodecolumn=false;
			boolean isNamecolumn=true;
			if(sourcecolumn!=null&&!sourcecolumn.toLowerCase().equals(table.getKeycolumn().toLowerCase())){
				if(sourcecolumn.toLowerCase().equals(table.getCodecolumn().toLowerCase())){
					isKeycolumn=false;
					isCodecolumn=true;
				}
			}
			if(sourcedisplay!=null&&!sourcedisplay.toLowerCase().equals(table.getNamecolumn().toLowerCase())){
				isNamecolumn=false;
			}
				List<DicVO> list=service.findTableDateList(sourcetable.toLowerCase());
				List<Map>rlist=new ArrayList<Map>(list.size());
				KeysIndex keyIndex=new KeysIndex(sourcecolumn!=null&&!sourcecolumn.equals("")?sourcecolumn:"id",displayField==null?"name":displayField);
				for (DicVO dicVO : list) {
					UnmodifiableKeyMap map=new UnmodifiableKeyMap(keyIndex);
					if(isKeycolumn){
						map.putIndex(0, dicVO.getId());
					}else if(isCodecolumn){
						map.putIndex(0, dicVO.getCode());
					}else{
						map.putIndex(0, dicVO.get(sourcecolumn));
					}
					if(isNamecolumn){
						map.putIndex(1, dicVO.getName());
					}else{
						map.putIndex(1, dicVO.get(sourcedisplay));
					}	
				
					rlist.add(map);
				}
				return rlist;
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
		
		}
		
		return new LinkedList();
		
	}
	
}
